import request from '../utils/request';

let socket = null;

/**
 * 初始化WebSocket连接
 * @param {string} token - 用户认证令牌
 * @param {Function} onMessage - 接收消息的回调函数
 * @param {Function} onStatusChange - 状态变化的回调函数
 * @returns {Object} - WebSocket实例
 */
export const initWebSocket = (token, onMessage, onStatusChange) => {
  if (socket) {
    socket.close();
  }

  // 连接到 Netty WebSocket 服务器
  const wsUrl = `ws://localhost:9090/ws`;
  socket = new WebSocket(wsUrl);

  socket.onopen = () => {
    console.log('WebSocket连接成功');
    
    // 发送认证消息
    const authMessage = {
      type: 'AUTH',
      data: {
        token: token
      }
    };
    socket.send(JSON.stringify(authMessage));
  };

  socket.onclose = () => {
    console.log('WebSocket连接断开');
  };

  socket.onerror = (error) => {
    console.error('WebSocket连接错误:', error);
  };

  socket.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      
      switch (message.type) {
        case 'AUTH_RESPONSE':
          if (message.data.success) {
            console.log('WebSocket认证成功');
          } else {
            console.error('WebSocket认证失败');
          }
          break;
        case 'MESSAGE':
          if (onMessage) {
            onMessage(message.data);
          }
          break;
        case 'STATUS':
          if (onStatusChange) {
            onStatusChange(message.data);
          }
          break;
        case 'ERROR':
          console.error('WebSocket错误:', message.data.message);
          break;
        default:
          console.log('收到未知类型消息:', message);
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  };

  return socket;
};

/**
 * 发送消息
 * @param {Object} message - 消息对象
 * @returns {Promise} - 返回发送结果
 */
export const sendMessage = (message) => {
  return new Promise((resolve, reject) => {
    if (!socket || socket.readyState !== WebSocket.OPEN) {
      reject(new Error('WebSocket未连接'));
      return;
    }

    const messageData = {
      type: 'MESSAGE',
      data: {
        receiverId: message.receiverId,
        chatType: message.conversationType,
        contentType: message.contentType,
        content: message.content
      }
    };

    socket.send(JSON.stringify(messageData));
    
    // 由于原生WebSocket没有回调机制，我们直接resolve
    // 实际的消息确认会通过MESSAGE_ACK类型的消息返回
    resolve({ success: true });
  });
};

/**
 * 获取会话列表
 * @returns {Promise} - 返回会话列表
 */
export const getConversations = async () => {
  try {
    const response = await request.get('/conversations');
    // 这里的 response 已经过了拦截器，是 ApiResponse
    // 返回其 data 字段（会话数组）
    return response.data;
  } catch (error) {
    console.error('获取会话列表失败:', error);
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 获取私聊消息历史
 * @param {string} userId - 用户ID
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.size - 每页数量
 * @returns {Promise} - 返回消息历史
 */
export const getPrivateMessages = async (userId, params = { page: 1, size: 20 }) => {
  try {
    const response = await request.get(`/messages/private/${userId}`, { params });
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 获取群聊消息历史
 * @param {string} groupId - 群组ID
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.size - 每页数量
 * @returns {Promise} - 返回消息历史
 */
export const getGroupMessages = async (groupId, params = { page: 1, size: 20 }) => {
  try {
    const response = await request.get(`/messages/group/${groupId}`, { params });
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 标记消息为已读
 * @param {Array} messageIds - 消息ID数组
 * @returns {Promise} - 返回操作结果
 */
export const markMessagesAsRead = async (messageIds) => {
  try {
    const response = await request.post('/messages/read', { messageIds });
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 将会话标记为已读（重置未读计数，持久化到后端）
 * @param {string} conversationId
 */
export const markConversationAsRead = async (conversationId) => {
  try {
    const response = await request.put(`/conversations/${conversationId}/read`);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 撤回消息
 * @param {string} messageId - 消息ID
 * @returns {Promise} - 返回操作结果
 */
export const recallMessage = async (messageId) => {
  try {
    const response = await request.delete(`/messages/${messageId}`);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 上传文件
 * @param {File} file - 文件对象
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise} - 返回上传结果
 */
export const uploadFile = async (file, onProgress) => {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await request.post('/files/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(percentCompleted);
        }
      }
    });

    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 发起通话
 * @param {Object} callData - 通话数据
 * @param {string} callData.receiverId - 接收者ID
 * @param {string} callData.type - 通话类型 (AUDIO/VIDEO)
 * @returns {Promise} - 返回操作结果
 */
export const initiateCall = async (callData) => {
  try {
    const response = await request.post('/calls/initiate', callData);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 获取联系人列表
 * @returns {Promise} - 返回联系人列表
 */
export const getContacts = async () => {
  try {
    const response = await request.get('/users/contacts');
    return response.data;
  } catch (error) {
    console.error('获取联系人列表失败:', error);
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};
